<template lang="pug">
  .orgSelect
    el-popover(
      v-model="orgShow"
      placement="bottom-start"
      trigger="manual"
      popper-class="orgPopper"
    )
      el-input.orgInput(slot="reference" ref="searchInput" placeholder="请选择" v-model="valueTitle" :clearable="clearable" @input="inputHandle" @clear="clearHandle" @focus="orgShow = true")
        i(slot="suffix" class="el-icon-arrow-down")
      el-popover(
        v-model="scdShow"
        placement="right-start"
        trigger="manual"
        popper-class="orgPopper"
      )
        .listWrapper.orgList(v-loading="orgLoading" slot="reference")
          p(v-for="item in orgList" :key="item.medinsId" @click="sltHandle(item)" :class="{'active': valueId === item.medinsId || orgId === item.medinsId}") {{item.medinsName}}
        .listWrapper.deviceList(v-loading="scdLoading")
          p(v-for="item in scdList" @click="handleNodeClick(item)" :key="item.deptId") {{item.deptName}}
      p.tr
        el-pagination(
          background
          layout="prev, pager, next"
          :total="pagination.total"
          :page-size="pagination.pageSize"
          hide-on-single-page
          @current-change="page => getData(page)"
        )
</template>
<script>
import { getOrgList, getDeptList } from '@/api/dict'

export default {
  name: 'OrgSelect',
  props: {
    selectType: {
      type: Number,
      default: 1 // 默认机构选择，2为选择科室，3为选择设备
    },
    /* 初始值 */
    initId: {
      type: [Array, String],
      default: ''
    },
    /* 可清空选项 */
    clearable: {
      type: Boolean,
      default: () => { return false }
    },
    filterable: {
      type: Boolean,
      default: true
    },
    size: {
      type: String,
      default: 'small'
    },
    initName: {
      type: String,
      default: ''
    }
  },
  computed: {
    scdId () {
      return this.selectType === 2 ? 'deptId' : 'devId'
    }
  },
  data () {
    return {
      pagination: {
        total: 100, // 分页总数
        pager: 1,
        pageSize: 10
      },
      orgLoading: false,
      orgShow: false, // 机构选择弹框是否显示
      orgId: '', // 当选择设备时选择机构id
      valueId: '', // 初始值
      valueTitle: '',
      medinsName: '', // 搜索机构名称
      orgList: [],
      scdLoading: false,
      scdShow: false,
      scdList: [] // 二级弹出框列表
    }
  },
  created () {
    this.getData()
  },
  mounted () {
    const that = this
    // 监听点击事件，隐藏弹窗
    function orgHandler (e) {
      if (!e.target.className !== 'orgPopper' && e.target.className !== 'el-input__inner') {
        that.orgShow = false
        that.scdShow = false
      }
    }
    window.addEventListener('click', orgHandler)
    this.$on('hook:destroy', () => {
      window.removeEventListener('click', orgHandler)
    })
  },
  methods: {
    // 获取机构列表
    getData (page) {
      const { pagination: { pager, pageSize } } = this
      const pageNum = page || pager
      this.orgLoading = true
      // 防止二级弹窗出现，需隐藏,并清空其列表
      this.scdShow = false
      this.scdList = []
      getOrgList({ pageNum, pageSize }, { medinsName: this.medinsName }).then(res => {
        console.log(res)
        this.orgList = res.data || []
        this.pagination.total = res.recordCounts || 0
      }).finally(() => {
        this.orgLoading = false
      })
    },
    // 搜索
    inputHandle (val) {
      const that = this
      if (!this.orgLoading) {
        that.medinsName = val
        that.getData(1)
        this.orgShow = true
      }
    },
    // 机构选择
    sltHandle (node) {
      console.log(node)
      const { selectType } = this
      // 如果只是机构选择，则不显示二级弹窗
      if (selectType === 1) {
        this.handleNodeClick(node)
        return
      }
      this.scdShow = true
      this.orgId = node.medinsId
      const fn = selectType === 2 ? getDeptList : getDeptList
      this.scdLoading = true
      fn({ pageNum: 1, pageSize: 100 }, { medinsId: node.medinsId }).then(res => {
        this.scdList = res.data || []
        if (!this.scdList.length) {
          this.handleNodeClick(node, 1)
        }
      }).finally(() => {
        this.scdLoading = false
      })
    },
    // 清除选中
    clearHandle () {
      this.valueTitle = ''
      this.valueId = null
      this.$emit('valChange', null)
    },
    // 切换选项
    handleNodeClick (node, type = this.selectType) {
      if (node && !node.disabled) {
        console.log(node)
        const valueKey = type === 1 ? 'medinsId' : 'deptId'
        if (type === 1) {
          this.valueTitle = node.medinsName
        } else if (type === 2) {
          this.valueTitle = node.medinsName + '/' + node.deptName
        } else if (type === 3) {
          this.valueTitle = node.medinsName + '/' + node.deptName + '/' + node.devName
        }
        this.valueId = node[valueKey]
        this.$emit('valChange', type === 1 ? (!Array.isArray(this.initId) ? node[valueKey] : [node.medinsId]) : [node.medinsId, node[valueKey]])
        this.orgShow = false
        this.scdShow = false
      }
    }
  },
  watch: {
    initId: {
      handler (val) {
        if (Array.isArray(val) && val.length > 0) {
          const arr = val.filter(x => !!x)
          this.valueId = arr[val.length - 1]
        } else {
          this.valueId = val
        }
      },
      immediate: true
    },
    initName (val) {
      this.valueTitle = val
    }
  }
}
</script>
<style lang="scss" scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item{
  height: auto;
  // max-height: 340px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
  box-sizing: border-box
}

.el-select-dropdown__item.selected{
  font-weight: normal;
  background: #fff;
  color: $--color-text-regular;
}

.listWrapper {
  max-height: 186px;
  overflow: auto;

  p {
    padding: 5px 0;
    cursor: pointer;

    &.active{
      color: $--color-primary;
      font-weight: bold;
    }
  }
}
</style>
